# -*- coding:utf-8 -*-

import urllib2, re

from exscore.ChampTable import ChampTable
from exscore.Team import Team
from exscore.Game import Game

class Xscores(object):
    
    _url = ''
    _resultTblUrlFormat = r'http://www.xscores.com/LiveScore.do?state=prompt%sLeagueTeam&cid=%s&tsscid=%s'
    
    _reTable = re.compile(r'<table[^>]*>(.+?)</table>', re.S)
    _reTr    = re.compile(r'<tr[^>]*>(.+?)</tr>', re.S)
    _reTd    = re.compile(r'<td[^>]*>(.+?)</td>', re.S)
    _reDate  = re.compile(r'^<td[^>]*>\s*<b>(\d+-\d+-\d+)</b></td>$')
    _reTags  = re.compile(r'<[^>]*?>')
    
    def __init__(self, url):
        self._url = url
        
    def getChampTable(self):
        
        champTable = ChampTable()
        
        result   = self._requestUrl(self._url)
        gameType = self._getGameTypeName()
        
        champTable.setGameType(gameType)
        
        for (cid, tsscid) in re.findall(r'javascript\:showTeam\((\d+)\, (\d+)\)\;', result, re.I):
            team = self._getTeam(self._resultTblUrlFormat % (gameType, cid, tsscid))
            champTable.addTeam(team)
            
        return champTable

        
    def _getTeam(self, url):
        result = self._requestUrl(url)

        team = Team()
        
        hasName = False 
        
        table = self._reTable.findall(result)[1]
    
        date   = None
        num    = 0
        for row in self._reTr.findall(table):
            
            dateMatch = self._reDate.findall(row)
            if dateMatch:
                date = dateMatch[0]
            elif date:
                game = Game(date)
                num  += 1
                
                cells = self._reTd.findall(row)
                
                if not hasName:
                    hasName = True
                    match = re.findall(r'<b>(.+?)</b>', cells[4])
                    if (match):
                        team.setName(re.sub(r'<[^>]*?>', '', match[0]))
                    else:
                        team.setName(re.sub(r'<[^>]*?>', '', cells[5]))
                        
                
                game.setNumber(num)
                game.setHomeTeam(re.sub(r'<[^>]*?>', '', cells[4]))
                game.setGuestTeam(re.sub(r'<[^>]*?>', '', cells[5]))
                game.setScoreLine(cells[12])
                
                team.addGame(game)
        
        return team

    
    def _getGameTypeName(self):
        return re.search('state=prompt(\w+)Table', self._url).group(1)

    
    def _requestUrl(self, url):
        return (urllib2
            .urlopen(urllib2.Request(url, None, { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)' }))
            .read()
            .decode('windows-1251'))
    
        
